import { Injectable } from '@nestjs/common';
import * as fs from 'fs';
import * as path from 'path';
import type { Multer } from 'multer';

export interface Image {
  id: string;
  filename: string;
  originalName: string;
  mimeType: string;
  size: number;
  url: string;
  uploadedBy: string;
  createdAt: string;
}

@Injectable()
export class ImageService {
  private readonly imagesFile = path.join(process.cwd(), 'data', 'images.json');
  private readonly uploadDir = path.join(process.cwd(), 'uploads');

  constructor() {
    const dataDir = path.join(process.cwd(), 'data');
    if (!fs.existsSync(dataDir)) {
      fs.mkdirSync(dataDir, { recursive: true });
    }

    if (!fs.existsSync(this.imagesFile)) {
      fs.writeFileSync(this.imagesFile, JSON.stringify([]));
    }

    if (!fs.existsSync(this.uploadDir)) {
      fs.mkdirSync(this.uploadDir, { recursive: true });
    }
  }

  private readImages(): Image[] {
    const data = fs.readFileSync(this.imagesFile, 'utf8');
    return JSON.parse(data);
  }

  private writeImages(images: Image[]): void {
    fs.writeFileSync(this.imagesFile, JSON.stringify(images, null, 2));
  }

  findAll(): Image[] {
    return this.readImages();
  }

  findById(id: string): Image | undefined {
    const images = this.readImages();
    return images.find(image => image.id === id);
  }

  findByUserId(userId: string): Image[] {
    const images = this.readImages();
    return images.filter(image => image.uploadedBy === userId);
  }

  saveImage(file: Multer.File, userId: string): Image {
    const images = this.readImages();
    
    const newImage: Image = {
      id: Date.now().toString(),
      filename: file.filename,
      originalName: file.originalname,
      mimeType: file.mimetype,
      size: file.size,
      url: `/uploads/${file.filename}`,
      uploadedBy: userId,
      createdAt: new Date().toISOString(),
    };
    
    images.push(newImage);
    this.writeImages(images);
    
    return newImage;
  }

  delete(id: string): boolean {
    const images = this.readImages();
    const imageIndex = images.findIndex(image => image.id === id);
    
    if (imageIndex === -1) return false;
    
    const image = images[imageIndex];
    const imagePath = path.join(this.uploadDir, image.filename);
    
    // 删除文件系统中的图片
    if (fs.existsSync(imagePath)) {
      fs.unlinkSync(imagePath);
    }
    
    // 从记录中删除
    images.splice(imageIndex, 1);
    this.writeImages(images);
    
    return true;
  }
}